package com.shallowUniverse.dmp.netty.server;

import com.shallowUniverse.dmp.netty.channel.NettyChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Shuai Guo
 * @version 1.0
 * @description
 * @date 2021/8/5
 */
@Slf4j
public class NettyServer {

    public void start(int port) throws Exception {
        //定义监听线程和工作线程
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        //初始化服务
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new NettyChannelInitializer())
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
        //绑定端口号
        ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
        log.info("Netty服务器已启动，监听端口为：" + port);
        //监听结束
        channelFuture.channel().closeFuture().sync();
    }
}
